<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件 -->
      <PageTools isShow>
        <template #before>
          <span>共{{ page.total }}条数据</span>
        </template>

        <template #after>
          <el-button size="small" type="success" @click="$router.push({name: 'UploadExcel'})">excel导入</el-button>
          <el-button size="small" type="danger" @click="exportData">excel导出</el-button>
          <el-button size="small" type="primary" @click="isShow = true" :disabled="!checkPermission('')">
            <i class="el-icon-plus" />
            新增员工
          </el-button>
        </template>
      </PageTools>

      <el-card v-loading="loading">
        <!-- 表格 -->
        <el-table border :data="list">
          <el-table-column
            label="序号"
            sortable
            type="index" />
          <el-table-column
            label="姓名"
            sortable
            prop="username" />
            <el-table-column
              label="头像"
              sortable
              prop="username"
              align="center">
            <template v-slot="{row}">
              <img
                @click="qrcodeShowBtn(row.staffPhoto)"
                v-imagerror="require('@/assets/common/圣诞节 4k.jpg')" 
                :src="row.staffPhoto" alt="" 
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px">
            </template>
          </el-table-column>
          <el-table-column
            label="工号"
            sortable
            prop="workNumber" />
          <!-- 
            formatter 用来格式化内容 
            prop 对应列内容的字段名，也可以使用 property 属性
          -->

          <el-table-column
            label="聘用形式"
            sortable
            :formatter="formatEmployment"
            prop="formOfEmployment" />
          <el-table-column
            label="部门"
            sortable
            prop="departmentName" />
          <el-table-column
            label="入职时间"
            sortable
            prop="timeOfEntry"
            >

            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>

          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable
            prop="enableState" >

          <template v-slot="{row}">
            <el-switch :value="row.enableState === 1"  />
          </template>

          </el-table-column>
          <el-table-column
            label="操作"
            sortable
            fixed="right" 
            width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push({
                  name: 'details', params: { id: row.id }, props: {
                    id: row.id
                  }
                })">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="change">
          </el-pagination>
        </el-row>
      </el-card>

      <addEmployee :isShow.sync="isShow" />
      <el-dialog title="二维码" :visible.sync="qrcodeShow">
        <el-row type="flex" justify="center">
          <canvas ref="canvas"></canvas>
        </el-row>
      </el-dialog>

      <assignRole ref="assignRole" :userId="userId" :roleShow.sync="roleShow" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from "./components/add-employee";
import assignRole from "./components/assign-role";
import { formatDate } from "@/filters";
import QrCode from 'qrcode'
export default {
  name: 'employees',
  data() {
    return {
      list: [], // 员工数据
      page: {
        page: 1,
        size: 10,
        total: 0 // 总数
      },
      loading: false, // 加载状态
      isShow: false, // 弹出框的状态
      qrcodeShow: false, // 二维码的弹框
      roleShow: false, // 分配角色的弹框
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    async delEmployee(id) {
      try {
        await this.$confirm('确认删除该员工吗?')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error);
      }
    },
    change(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      // console.log(cellValue);
      const str = EmployeeEnum.hireType.find(item => item.id === cellValue) || {value: '未知'}
      return str.value
    },
    // 将excel导出的方法
    async exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']] // 根据表格的数据来
      const merges = ['A1:A2', 'B1:F1', 'G1:G2'] // 根据表格的选项来进行合并
      import('@/vendor/Export2Excel').then(async excel => {
        // 取巧 直接一页获取全部数据
        const { rows } = await getEmployeeList({page: 1, size: this.page.total})
        const data = this.formatJson(headers,rows)
        // excel 文件导出对象
        excel.export_json_to_excel({
          header: Object.keys(headers), // 导出Excel的表格标题 必填
          data, // 导出Excel的表格数据 必填
          filename: '员工资料表', // 导出文件名
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
    },
    // 将[{}] 转成 [[]] 的形式的方法
    formatJson(headers, rows) {
      // 返回转换好的[[...]]
      return rows.map(item => {
        // item: 数组每一页的数组 {id: '1074238801402007552', mobile: '13400000002', …}
        // 返回[里面的数组]
        return Object.keys(headers).map(key => {
          // key: 中文名称
          // 数组对应的变量名 headers[key]  workNumber
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // item[headers[key]] 就是 每一项的值 也就是 value 
            // item[headers[key]] = item.属性名
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const str = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]]) || {value:'未知'}
            return str.value
          }
          // 返回[[里面的值]]
          return item[headers[key]]
        })
      })
    },
    // 二维码
    qrcodeShowBtn(url) {
      if (!url) return this.$message.warning('该用户没有头像!')
      // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
      this.qrcodeShow = true
      // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
      this.$nextTick(() => {
         // 此时可以确认已经有ref对象了
        QrCode.toCanvas(this.$refs.canvas, url) // 将地址转化成二维码
        // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
      })
    },
    async editRole(id) {
      // 这里为什么加 await 因为数据更新是异步最后等待数据的更新
      await this.$refs.assignRole.getUserDetailById(id)
      this.userId = id
      this.roleShow = true
    } 
  },
  components: {
    addEmployee,
    assignRole
  }
}
</script>

<style scoped>

</style>
